﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ERP.WebUI
{
    /// <summary>
    /// 记录动作Log
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class AdminOperateLogAttribute : ActionFilterAttribute
    {
        public PermissionRepository permissionRepository = new PermissionRepository();
        public OperateLogRepository operateLogRepository = new OperateLogRepository();

        public AdminOperateLogAttribute()
        {
        }


        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var user = SessionHelper.GetSession("CurrentUser") as User;
            if (user != null)
            {
                var area = filterContext.RouteData.DataTokens["area"] != null ? filterContext.RouteData.DataTokens["area"].ToString() : "";
                var controller = filterContext.RouteData.Values["controller"].ToString();
                var action = filterContext.RouteData.Values["action"].ToString();
                var actionName = action.ToLower();
                var permission = permissionRepository.Permissions.FirstOrDefault(t => t.Code.ToLower() == actionName && t.Enabled == true && t.IsDeleted == false);
                var description = string.Empty;
                if (permission != null)
                {
                    description = permission.Name;
                }

                var model = new OperateLogModel
                {
                    Area = area,
                    Controller = controller,
                    Action = action,
                    Description = description,
                    LogTime = DateTime.Now,
                    UserId = user.Id,
                    LoginName = user.LoginName,
                    IPAddress = Tools.GetUserIp()
                };

                operateLogRepository.Insert(model);
            }
        }
    }
}